package srv

import (
	"background/http/api/dto"
	"background/model/back/entity"
	"background/model/back/repo"
	"background/utilx/cachex"
	"context"
	"github.com/redis/go-redis/v9"
	"gorm.io/gen"
)

type CloudPayment struct {
	db     repo.Query
	bucket cachex.RedisBucket
	redisx *redis.Client
}

func newCloudPayment(db repo.Query, bucket cachex.RedisBucket) CloudPayment {
	redisx := bucket.GetClient(entity.CacheTypeCategory)
	return CloudPayment{db: db, bucket: bucket, redisx: redisx}
}

func (r CloudPayment) DelById(ctx context.Context, id int64) (gen.ResultInfo, error) {
	return r.db.CloudPayment.WithContext(ctx).Where(repo.CloudPayment.ID.Eq(id)).Delete()
}
func (r CloudPayment) GetById(ctx context.Context, id int64) (*entity.CloudPayment, error) {
	userInfo, err := r.db.CloudPayment.WithContext(ctx).Where(repo.CloudPayment.ID.Eq(id)).First()
	if err != nil {
		return nil, err
	}
	return userInfo, err
}
func (r CloudPayment) InsertOne(ctx context.Context, rec entity.CloudPayment) error {
	return r.db.CloudPayment.WithContext(ctx).Create(&rec)
}
func (r CloudPayment) GetBySelf(ctx context.Context, rec dto.SearchWithPage[entity.CloudPayment]) (dto.PageResult[entity.CloudPayment], error) {
	page := rec.PageInfo
	do := r.db.CloudPayment.WithContext(ctx).Debug()

	if len(rec.Data.Name) > 0 {
		do.Where(repo.CloudPayment.Name.Like(rec.Data.Name + "%"))
	}

	if len(rec.Data.Payment) > 0 {
		do.Where(repo.CloudPayment.Payment.Like(rec.Data.Payment + "%"))
	}

	byPage, i, err := do.FindByPage(int(page.Start()), int(page.PageSize))
	if err != nil {
		return dto.PageResult[entity.CloudPayment]{}, err
	}
	return dto.PageResult[entity.CloudPayment]{
		Items: byPage,
		Total: i,
	}, nil
}
func (r CloudPayment) UpdateById(ctx context.Context, u *entity.CloudPayment) error {
	err := r.db.CloudPayment.WithContext(ctx).Where(repo.CloudPayment.ID.Eq(u.ID)).Save(u)
	if err != nil {
		return err
	}
	return nil
}
